// UDP Client.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <hash_map>
#include <conio.h>
#include "../UDP Lib/RUdpSocket.h"

RUdpSocket* gSocket;
int gLastKnownAck = 0;
bool gShutdown = false;
bool gHandshakeAck = false;

DWORD WINAPI ReceiveThread(LPVOID param)
{
  __int64 data = 0;

  int seqId;

  while ( !gShutdown )
  {
    if ( gSocket->Receive((char*) &seqId, sizeof(seqId)) > 0 )
    {
      std::cout << seqId << std::endl;

      gLastKnownAck++;
    }
  }

  return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
  WSADATA wsaData;
  WSAStartup(MAKEWORD(2,2), &wsaData);

  gSocket = new RUdpSocket;

  if ( gSocket->Connect("127.0.0.1", 5000) == 0 )
  {
    HANDLE t = CreateThread(NULL, 0, ReceiveThread, NULL, 0, 0);

    int totalPackets = 50;
    int firstPacket = 10;
    gLastKnownAck = 0;

    // Blast through the original packets
    for (long i=firstPacket; i<totalPackets + firstPacket; ++i)
    {
      gSocket->SendTo( (char*) &i, sizeof(i) );
    }

    while (gLastKnownAck < totalPackets)
    {
      Sleep(1);
    }

    gShutdown = true;
    gSocket->Close();

    WaitForSingleObject(t, INFINITE);
    CloseHandle(t);
  }

  WSACleanup();

  std::cout << "Completed..." << std::endl;

  while (!_kbhit())
    Sleep(1);

  return 0;
}
